package com.coolw.data.migrate.process.strategy;

import com.coolw.data.migrate.enums.MigrateTypeEnum;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.text.StrUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据迁移Context
 *
 * @author coolw
 * @date 2024/2/6 16:20
 */
@Component
public class DataMigrateContext implements InitializingBean, DisposableBean {

    @Resource
    private ApplicationContext applicationContext;

    private Map<MigrateTypeEnum, DataMigrateProcess> dataMigrateProcessMap;

    public DataMigrateProcess getProcess(String type) {
        MigrateTypeEnum mtEnum = MigrateTypeEnum.getEnum(type);
        Assert.notNull(mtEnum, StrUtil.format("{} 未匹配到数据迁移类型", type));

        return dataMigrateProcessMap.get(mtEnum);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, DataMigrateProcess> beanMap = applicationContext.getBeansOfType(DataMigrateProcess.class);
        dataMigrateProcessMap = beanMap.values().stream()
                .collect(Collectors.toMap(DataMigrateProcess::type, b -> b));
    }

    @Override
    public void destroy() throws Exception {
        dataMigrateProcessMap = null;
        applicationContext = null;
    }
}
